﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lyh.XianGuo.Reader.Exchange;

namespace Lyh.XianGuo.Reader
{
    public partial class DownloadForm : Form
    {
        private string errorMessge = string.Empty;
        public DownloadForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy) return;
            btnDownload.Enabled = false;
            progressBar.Visible = true;
            backgroundWorker.RunWorkerAsync();
        }

        private void Download()
        {
            var url = string.Format("http://xianguo.com/book/detail/{0}", txtUrl.Text.Trim());
            var analyze = new Analyze(url);
            analyze.OnPageDownloaded += analyze_OnPageDownloaded;
            var book = analyze.ExtractBookInfo();
            progressBar.Maximum = book.Count;
            analyze.SaveBookInfo(book);
            analyze.ExtractBookContent(book);
        }

        void analyze_OnPageDownloaded(int pageIndex)
        {
            progressBar.Value = pageIndex;
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Download();
            }
            catch (Exception ex)
            {
                errorMessge = ex.Message;
            }
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnDownload.Enabled = true;
            progressBar.Visible = false;
            MessageBox.Show(string.IsNullOrWhiteSpace(errorMessge) ? "下载成功" : errorMessge);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        private void DownloadForm_Load(object sender, EventArgs e)
        {

        }
    }
}
